package com.igeek.d0619.test3;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @Author: zhiyu
 * @Date:18:00
 * @DESC:
 */
public class JdkProxy {
    private UserService targrt;

    public JdkProxy(UserService targrt) {
        this.targrt = targrt;
    }
    public InterfaceProxy getProxy(){
        ClassLoader classLoader = targrt.getClass().getClassLoader();
        Class<?>[] interfaces = targrt.getClass().getInterfaces();
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("开始日志记录，追踪的方法是"+method.getName()+"args="+ Arrays.toString(args));
                long start = System.currentTimeMillis();

                Object result = method.invoke(targrt, args);

                long end = System.currentTimeMillis();
                System.out.println("结束日志追踪，，追踪的方法是"+method.getName()+",执行结果是"+result+"此方法耗时="+(end-start)/1000.0+"s");
                return result;
            }
        };
        Object proxy = Proxy.newProxyInstance(classLoader, interfaces, handler);
        return (InterfaceProxy) proxy;
    }
}
